package io.xxx.walle.assistant;

import io.xxx.walle.config.RateLimiterManager;
import io.xxx.walle.exception.NoTokenException;
import io.xxx.walle.wechaty.RobotClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Optional;

@Slf4j
@Service
public class AssistantService {

    @Resource
    private AssistantRepository assistantRepository;

    @Resource
    private TokenRepository tokenRepository;

    @Resource
    private TokenService tokenService;

    @Resource
    private RateLimiterManager rateLimiterManager;

    @Resource
    private RobotClient robotClient;

    /**
     * 制作一个小助手
     */
    public void createRobot() throws IOException {
        Optional<Token> token = tokenRepository.findByUsed(false);
        if (token.isEmpty()) {
            throw new NoTokenException();
        }
        robotClient.create(token.get());
    }

    /**
     * 小助手登录后需要保存小助手登录信息
     */
    public void save(Assistant assistant) {
        rateLimiterManager.add(assistant.getOutId());
        assistantRepository.save(assistant);
        tokenService.useToken(assistant.getToken());
    }

    /**
     * 小助手登出后需要保存小助手登出信息
     */
    public void logout(Assistant assistant) {
    }

    /**
     * 删除一个小助手
     */
    public void remove() {

    }

    /**
     * 分配小助手
     */
    public Assistant assign(Long storeId, Integer provinceId, Integer cityId) {
        return assistantRepository.findFirstByEnabledEquals(true);
    }
}
